package com.jchao.process.service.impl;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jchao.model.process.ProcessTemplate;
import com.jchao.model.process.ProcessType;
import com.jchao.process.mapper.ProcessTemplateMapper;
import com.jchao.process.service.ProcessService;
import com.jchao.process.service.ProcessTemplateService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jchao.process.service.ProcessTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 审批模板 服务实现类
 * </p>
 *
 * @author jchao
 * @since 2023-11-17
 */
@Service
public class ProcessTemplateServiceImpl extends ServiceImpl<ProcessTemplateMapper, ProcessTemplate> implements ProcessTemplateService {

    @Autowired
    private ProcessTemplateMapper processTemplateMapper;

    @Autowired
    private ProcessService processService;

    @Override
    public IPage<ProcessTemplate> selectPage(Page<ProcessTemplate> pageParam) {
        return processTemplateMapper.selectPage(pageParam);
//        return this.selectPage2(pageParam);
    }


    @Transactional
    @Override
    public void publish(Long id) {
        ProcessTemplate processTemplate = this.getById(id);
        processTemplate.setStatus(1);
        processTemplateMapper.updateById(processTemplate);

        //TODO 部署流程定义，后续完善
        String processDefinitionPath = processTemplate.getProcessDefinitionPath();
        if (!StringUtils.isEmpty(processDefinitionPath)) {
            processService.deployByZip(processDefinitionPath);
        }
    }


    @Autowired
    private ProcessTypeService processTypeService;

    public IPage<ProcessTemplate> selectPage2(Page<ProcessTemplate> pageParam) {
        Page<ProcessTemplate> page = this.page(pageParam);
        List<ProcessTemplate> records = page.getRecords();
        Map<Long, String> processTypeMap = processTypeService.list().stream().collect(Collectors.toMap(ProcessType::getId, ProcessType::getName));
         records = records.stream().map(processTemplate -> {
            String name = processTypeMap.get(processTemplate.getProcessTypeId());
            processTemplate.setProcessTypeName(name);
            return processTemplate;
        }).collect(Collectors.toList());
       return page;
    }
}
